package com.scau.controller;

import com.scau.entity.*;
import com.scau.repository.OrderDetailRepository;
import com.scau.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Value("${server.port}")
    private String port;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @GetMapping("/port")
    public String port(){
        return this.port;
    }

    @GetMapping("/findByUId/{index}/{limit}/{uid}")
    public OrderVO findByUId(@PathVariable("index") int index, @PathVariable("limit") int limit,@PathVariable("uid") int uid){
        List<Order> list = orderRepository.findByUId(index,limit,uid);
        return new OrderVO(0,"",orderRepository.countByUid(uid),list);
    }

    @GetMapping("/findAll/{index}/{limit}")
    public OrderVO findAll(@PathVariable("index") int index, @PathVariable("limit") int limit){
        System.out.println(index + " " +  limit);
        List<Order> list = orderRepository.findAll(index, limit);
        return new OrderVO(0,"",orderRepository.count(),list);
    }


    //获得最新一次订单
    @GetMapping("/getLatestOrderId/{uid}")
    public int getLatestOrderId(@PathVariable("uid") int uid){
        int orderId = orderRepository.getLatestOrderId(uid);
//        if(orderId == null)
        return orderRepository.getLatestOrderId(uid);
    }

    @PostMapping(value = "/save",produces = "application/json;charset=UTF-8;")
    public void save(@RequestBody PayForm payForm){
        System.out.println(payForm);
        Order order = payForm.getOrder();
        order.setDate(new Date());
        List<OrderDetail> list = payForm.getList();
        orderRepository.save(order);
        int orderId = orderRepository.getLatestOrderId(order.getUid());
        for(int i = 0; i < list.size() ; i++){
            OrderDetail orderDetail = list.get(i);
            orderDetail.setOrderId(orderId);
            orderDetailRepository.save(orderDetail);
        }
    }

    @PutMapping("/updateState/{orderId}/{state}")
    public void updateState(@PathVariable("orderId") int orderId, @PathVariable("state") int state){
        orderRepository.updateState(orderId,state);
    }

    @GetMapping("/orderdetail/findByOrderId/{index}/{limit}/{orderId}")
    public OrderDetailVO findAllByOrderId(@PathVariable("index") int index, @PathVariable("limit") int limit,@PathVariable("orderId") int orderId){
        List<OrderDetail> list = orderDetailRepository.findByOrderId2(index,limit,orderId);
        return new OrderDetailVO(0,"",orderDetailRepository.countByOrderId(orderId),list);
    }


    /**
     * 1.某件商品月销售量
     * 2.所有商品月销售量
     * 3.人工智能？
     *
     *
     */
}
